/**
 * 
 */
package com.bolbachchan.blog.dao.common;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

/**
 * @author Chaitanya
 * 
 */
public class BaseDAO {

    private SessionFactory sessionFactory;
    private Map<String, Object> parameterMap;

    public void setSessionFactory(SessionFactory sessionFactory) {
	this.sessionFactory = sessionFactory;
    }

    /**
     * @return the sessionFactory
     */
    public SessionFactory getSessionFactory() {
	return sessionFactory;
    }

    /**
     * @return
     */
    protected Map<String, Object> getParameterMap() {
	if (parameterMap == null) {
	    parameterMap = new HashMap<String, Object>();
	}
	return parameterMap;
    }

    /**
     * 
     */
    protected void clearParameterMap() {
	parameterMap.clear();
    }

    /**
     * @param queryName
     * @param values
     * @return
     * @throws Exception
     */
    protected Query getNamedQuery(String queryName, Map<String, Object> parameterValues) throws Exception {
	Query query = null;
	try {
	    query = getSessionFactory().getCurrentSession().getNamedQuery(queryName);

	    String[] keys = parameterValues.keySet().toArray(new String[0]);
	    for (int i = 0; i < parameterValues.size(); i++) {
		query.setParameter(keys[i], parameterValues.get(keys[i]));
	    }
	    return query;
	}
	catch (Exception e) {
	    throw new Exception("Exception retrieving named query using query name and array of values");
	}
    }
}
